<?php


namespace app\api\controller;
use app\common\controller\Api;
use Overtrue\Pinyin\Pinyin;
use think\Db;
use think\facade\Env;
use think\facade\Log;
use fast\Http;
class Live extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = '*';
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    public function  create()
    {
        $post = $this->request->post();
        if(!empty($post))
        {
            $app_id = $post['app_id']??'';
            $app_secret = $post['app_secret']??'';
            $title = $post['title']??''; //直播名称
            if(empty($title) || strlen($title) <= 3 || strlen($title) > 30)
            {
                $this->error('直播名称必须(长度3-30之间)');
            }
            if(!empty($app_id) && !empty($app_secret))
            {
                $app =  Db::name('app')->where([['app_id','=',$app_id],['app_secret','=',$app_secret]])->find();
                if(!empty($app))
                {

                    $stream = $post['stream']??''; //唯一的设备码,如果没传系统生成一个唯一的
                    $have =  Db::name('live')
                        ->where([['app_id','=',$app['id']],['user_id','=',$app['user_id']],['title','=',$title]])
                        ->field('id')->find();
                    if(!empty($have))
                    {
                        $this->error('直播名称重复');
                    }
                    if(!empty($stream))
                    {
                        $stream_have =  Db::name('live')
                            ->where([['app_id','=',$app['id']],['user_id','=',$app['user_id']],['stream','=',$stream]])
                            ->field('id')->find();
                        if(!empty($stream_have))
                        {
                            $this->error('设备唯一码重复,请不要重复创建');
                        }
                    }
                    else
                    {
                        $pinyin = new Pinyin();
                        $text = $title;
                        $initials = $pinyin->abbr($text); // 获取首字母缩写
                        $stream = $initials.time();
                    }

                    $data = [
                        'title'=>$title,
                        'stream'=>$stream,
                        'app_id'=>$app['id'],
                        'user_id'=>$app['user_id'],
                        'status'=>'normal',
                        'live_status'=>'0',
                        'create_time'=>date('Y-m-d H:i:s'),
                        'publish_url'=>'rtmp://'.Env::get('liveserver.ip').'/'.$app['app_name'].'/'.$stream,
                        'rtmp_play_url'=>'rtmp://'.Env::get('liveserver.ip').'/'.$app['app_name'].'/'.$stream,
                        'flv_play_url'=>'http://'.Env::get('liveserver.ip').':'.Env::get('liveserver.httpport').'/'.$app['app_name'].'/'.$stream.'.live.flv',
                        'hls_play_url'=>'http://'.Env::get('liveserver.ip').':'.Env::get('liveserver.httpport').'/'.$app['app_name'].'/'.$stream.'/hls.m3u8',
                        'webrtc_play_url'=>'http://'.Env::get('liveserver.ip').':'.Env::get('liveserver.httpport').'/index/api/webrtc?app='.$app['app_name'].'&stream='.$stream.'&type=play',
                    ];
                    $id =  Db::name('live')->insertGetId($data);
                    if($id > 0)
                    {
                        $data['id'] = $id;
                        $timeStamp = Env::get('liveserver.timestamp');

                        $push_key = Env::get('liveserver.push_key');

                        $play_key = Env::get('liveserver.play_key');

                        //推流key -- app_id -- live_id -- user_id
                        $push_key_str = $push_key.'-'.$data['app_id'].'-'.$id.'-'.$data['user_id'];
                        $publish_auth_key = '/'.$app['app_name'].'/'.$data['stream'].'-'.$timeStamp.'-0-0-'.$push_key_str;
                        $push_auth_key = encrypt($publish_auth_key,'E',Env::get('liveserver.encrypt_key'));
                        $data['publish_url'] = $data['publish_url'].'?auth_key='.$push_auth_key;
                        //拉流key -- app_id -- live_id -- user_id
                        $play_key_str = $play_key.'-'.$data['app_id'].'-'.$id.'-'.$data['user_id'];
                        $plays_auth_key = '/'.$app['app_name'].'/'.$data['stream'].'-'.$timeStamp.'-0-0-'.$play_key_str;
                        $play_auth_key = encrypt($plays_auth_key,'E',Env::get('liveserver.encrypt_key'));
                        $data['rtmp_play_url'] = $data['rtmp_play_url'].'?auth_key='.$play_auth_key;
                        $data['flv_play_url'] = $data['flv_play_url'].'?auth_key='.$play_auth_key;
                        $data['hls_play_url'] = $data['hls_play_url'].'?auth_key='.$play_auth_key;
                        $data['webrtc_play_url'] = $data['webrtc_play_url'].'&auth_key='.$play_auth_key;
                        $this->success('创建直播服务成功',$data);
                    }
                    else
                    {
                        $this->error('服务器繁忙,请重试');
                    }
                }
                else
                {
                    $this->error('app_id 与 app_secret  验证错误');
                }
            }
            else
            {
                $this->error('app_id 与 app_secret必须');
            }
        }
        else
        {
            $this->error('参数错误');
        }
    }

    public function query()
    {
        $post = $this->request->post();
        if(!empty($post))
        {
            $app_id = $post['app_id']??'';
            $app_secret = $post['app_secret']??'';
            $stream = $post['stream']??''; //直播流
            if(empty($stream))
            {
                $this->error('设备码必须');
            }
            if(!empty($app_id) && !empty($app_secret))
            {
                $app =  Db::name('app')->where([['app_id','=',$app_id],['app_secret','=',$app_secret]])->find();
                if(!empty($app))
                {
                    $data =  Db::name('live')
                        ->where([['app_id','=',$app['id']],['user_id','=',$app['user_id']],['stream','=',$stream]])
                        ->field('*')->find();
                    if(!empty($data))
                    {
                        $timeStamp = Env::get('liveserver.timestamp');

                        $push_key = Env::get('liveserver.push_key');

                        $play_key = Env::get('liveserver.play_key');

                        //推流key -- app_id -- live_id -- user_id
                        $push_key_str = $push_key.'-'.$data['app_id'].'-'.$data['id'].'-'.$data['user_id'];
                        $publish_auth_key = '/'.$app['app_name'].'/'.$data['stream'].'-'.$timeStamp.'-0-0-'.$push_key_str;
                        $push_auth_key = encrypt($publish_auth_key,'E',Env::get('liveserver.encrypt_key'));
                        $data['publish_url'] = $data['publish_url'].'?auth_key='.$push_auth_key;
                        //拉流key -- app_id -- live_id -- user_id
                        $play_key_str = $play_key.'-'.$data['app_id'].'-'.$data['id'].'-'.$data['user_id'];
                        $plays_auth_key = '/'.$app['app_name'].'/'.$data['stream'].'-'.$timeStamp.'-0-0-'.$play_key_str;
                        $play_auth_key = encrypt($plays_auth_key,'E',Env::get('liveserver.encrypt_key'));
                        $data['rtmp_play_url'] = $data['rtmp_play_url'].'?auth_key='.$play_auth_key;
                        $data['flv_play_url'] = $data['flv_play_url'].'?auth_key='.$play_auth_key;
                        $data['hls_play_url'] = $data['hls_play_url'].'?auth_key='.$play_auth_key;
                        $data['webrtc_play_url'] = $data['webrtc_play_url'].'?auth_key='.$play_auth_key;
                        $this->success('查询直播服务成功',$data);
                    }
                    else
                    {
                        $this->error('暂无与'.$stream.'相关的直播信息');
                    }

                }
                else
                {
                    $this->error('app_id 与 app_secret  验证错误');
                }
            }
            else
            {
                $this->error('app_id 与 app_secret必须');
            }
        }
        else
        {
            $this->error('参数错误');
        }
    }


    public function add_ffmpeg()
    {
        $post = $this->request->post();
        if(!empty($post))
        {
            $src_url = $post['src_url'];
            $dst_url = $post['dst_url'];
            $timeout_ms = $post['timeout_ms']??10000;
            $enable_hls =  $post['enable_hls']??0;
            $enable_mp4 =  $post['enable_mp4']??0;
            if(!empty($src_url) && !empty($dst_url))
            {

                $url = 'http://'.Env::get('liveserver.ip').':'.Env::get('liveserver.httpport').'/index/api/addFFmpegSource?secret='.Env::get('liveserver.secret').'&src_url='.urlencode($src_url).'&dst_url='.urlencode($dst_url).'&timeout_ms='.$timeout_ms.'&enable_hls='.$enable_hls.'&enable_mp4='.$enable_mp4;
                $res = Http::get($url);
                if($res != false) {
                    $rs = json_decode($res, true);
                    Log::debug('add_ffmpeg_res');
                    Log::debug($res);
                    if ($rs['code'] == 0) {
                        $this->success('创建FFmpeg代理成功', $rs['data']);
                    } else {
                        $this->error($rs['msg'] . '[code:' . $rs['code'] . ']');
                    }
                }
                else
                {
                    $this->error('添加FFmpeg代理响应超时,请检查拉流地址信号是否正常');
                }
            }
            else
            {
                $this->error('拉流地址和推流地址必填');
            }
        }
        else
        {
            $this->error('参数错误');
        }
    }

}